package com.controleFamiliar.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.controleFamiliar.pojo.CategoriaDespesa;
import com.controleFamiliar.util.HibernateUtil;

public class CategoriaDespesaDAO extends GenericDAO<Integer, CategoriaDespesa>{
	
	@SuppressWarnings("unchecked")
	public List<CategoriaDespesa> listarTodasCategorias(){
		List<CategoriaDespesa> lista = new ArrayList<CategoriaDespesa>();
		try{
			Session session = HibernateUtil.getSessionFactory().openSession();
			StringBuilder sb = new StringBuilder();
			sb.append("FROM CategoriaDespesa");
			Query q = session.createQuery(sb.toString());
			lista = q.list();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{HibernateUtil.getSessionFactory().close();}catch(Exception e){}
		}
		return lista;
	}
	
	public CategoriaDespesa obterCategoria(Integer codCategoria){
		CategoriaDespesa categoria = new CategoriaDespesa();
		try{
			Session session = HibernateUtil.getSessionFactory().openSession();
			StringBuilder sb = new StringBuilder();
			sb.append("FROM CategoriaDespesa "
					+ "WHERE codCategoriaDespesa = :codCategoria");
			Query q = session.createQuery(sb.toString());
			q.setInteger("codCategoria", codCategoria);
			categoria = (CategoriaDespesa)q.uniqueResult();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{HibernateUtil.getSessionFactory().close();}catch(Exception e){}
		}
		return categoria;
	}
	
	public void salvarCategoriaDespesa(CategoriaDespesa categoriaDespesa) throws Exception {
		try{
			Session session = HibernateUtil.getSessionFactory().openSession();
			CategoriaDespesa novaCategoria = new CategoriaDespesa();
			novaCategoria = categoriaDespesa;
			session.save(novaCategoria);
			session.flush();
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{HibernateUtil.getSessionFactory().close();}catch(Exception e){}
		}
	}
	
	public void removerCategoria(Integer codCategoria) throws Exception {
		try{
			Session session = HibernateUtil.getSessionFactory().openSession();
			String hql = "Delete From CategoriaDespesa where codCategoriaDespesa= :codCategoria";
			Query query = session.createQuery(hql);
			query.setInteger("codCategoria", codCategoria);
			int result = query.executeUpdate();
			System.out.println("Rows affected: " + result);
		}catch (Exception e){
			e.printStackTrace();
		}finally{
			try{HibernateUtil.getSessionFactory().close();}catch(Exception e){}
		}
	}

}
